import { createRouter, createWebHistory } from 'vue-router';

const Home = () => import('../views/Home.vue');
const UserDemo = () => import('../views/UserDemo.vue');
const Login = () => import('../views/Login.vue');

const routes = [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'Home',
      // 路由元信息
      meta: {
        requiresAuth: false,
        title: '首页'
      },
      component: Home,
      // 路由独享守卫
      beforeEnter: (to, from, next) => {
        console.log('即将进入首页');
        next();
      },
      // 路由 props 解耦
      props: (route) => ({ query: route.query.search })
    },
    {
      path: '/userDemo',
      name: 'UserDemo',
      meta: {
        requiresAuth: true,
        title: '用户demo'
      },
      component: UserDemo,
      beforeEnter: (to, from, next) => {
        console.log('即将进入用户demo');
        next();
      }
    },{
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        requiresAuth: false,
        title: '登录'
      },
      beforeEnter: (to, from, next) => {
        console.log('即将进入登录');
        next();
      }
    }
  ];


  const router = createRouter({
    history: createWebHistory(),
    routes,
    // 滚动行为
    scrollBehavior(to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { top: 0 };
      }
    }
  });
  
  // 全局前置守卫
  router.beforeEach((to, from, next) => {
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    next();
  });
  
  // 全局后置钩子
  router.afterEach((to, from) => {
    console.log('已进入路由:', to.name);
  });
  
  export default router;